import React from 'react';
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import AV from 'leancloud-storage'
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file){
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}

export default class ImgUpload extends React.Component {
  state = {
    loading: false,
  };
  handleUpload = (info)=>{
    getBase64(info.file, imageUrl =>{
        let data = {base64: imageUrl };
        const file = new AV.File('img.png', data);
        file.save().then(res=>{
            let imageUrl = res.attributes.url;
            this.setState({
                imageUrl,
                loading: false,
            })
            this.props.handlePath(imageUrl)
        })
    });
  }
  render() {
    const { loading, imageUrl } = this.state;
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    let {showImg,newImgUrl} = this.props;
    return (
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        beforeUpload={beforeUpload}
        customRequest={this.handleUpload}
      >
        {(imageUrl&&showImg) || newImgUrl ? <img src={imageUrl || newImgUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
      </Upload>
    );
  }
}
